package cn.itrip.auth.controller;

import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import cn.itrip.dto.Dto;
import cn.itrip.pojo.ItripUser;
import cn.itrip.vo.ItripUserVO;
import cn.itrip.vo.TokenVO;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import sun.dc.pr.PRError;
import ytx.org.apache.http.HttpRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.zip.DataFormatException;

@RestController  //Controller+responseBody
@RequestMapping(value = "/api")
@Api(value = "测试注册",tags = "{测试注册}")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;

    /**
     *    邮箱注册
     */
    @ApiOperation(value = "邮箱注册")
    @RequestMapping(value = "/doregister", method = RequestMethod.POST, produces = "application/json")
    public Dto doRegister(@RequestBody ItripUserVO vo) {
        try {
            //1.邮箱格式的验证
            if (!userService.validEmail(vo.getUserCode())) {
                return DtoUtil.returnFail("邮箱格式不正确请重新输入", ErrorCode.AUTH_ILLEGAL_USERCODE);
            }
            //2.添加用户信息
            Dto dto = userService.itriptxAddItripUser(vo);
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 手机注册
     */
    @ApiOperation(value = "手机注册")
    @RequestMapping(value = "/registerbyphone", method = RequestMethod.POST, produces = "application/json")
    public Dto registerByPhone(@RequestBody ItripUserVO vo) {
        try {
            //1.手机格式的验证
            if (!userService.validPhone(vo.getUserCode())) {
                return DtoUtil.returnFail("手机格式不正确请重新输入", ErrorCode.AUTH_ILLEGAL_USERCODE);
            }
            //2.添加用户信息
            Dto dto = userService.itriptxAddItripUser(vo);
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 验证是否已存在该用户名
     */
    @ApiOperation(value = "验证是否已存在该用户名")
    @RequestMapping(value = "/ckusr", method = RequestMethod.GET, produces = "application/json")
    public Dto ckusr(@RequestParam("name") String name) {
        try {
            //1.验证是否已存在该用户名
            if (userService.ckusr(name)) {
                return DtoUtil.returnSuccess();
            }else {
                return DtoUtil.returnFail("用户名已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 邮箱注册用户激活
     */
    @ApiOperation(value = "邮箱注册用户激活")
    @RequestMapping(value = "/activate", method = RequestMethod.PUT, produces = "application/json")
    public Dto activate(@RequestParam("user") String user,@RequestParam("code") String code) {
        try {
           return attributeUser(user,code);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }


    /**
     * 激活公共方法
     * @param user
     * @param code
     * @return
     * @throws Exception
     */
    public Dto attributeUser(String user ,String code) throws Exception {
        //用户是否存在
        if (!userService.ckusr(user)) {
            //1.验证用户名是否已激活
            if (userService.activate(user)){
                //2.验证激活码是否存在
                if (userService.activateIsNull("md5"+user,code)){
                    userService.deleteUser(user);
                    return DtoUtil.returnFail("激活码已失效请重新注册", ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }
                //3.验证激活码是否正确
                if (userService.activateCkusr("md5"+user,code)){
                    //4.激活用户
                    if (userService.updateActivateByCode(user)){
                        return DtoUtil.returnSuccess();
                    }else {
                        return DtoUtil.returnFail("激活异常", ErrorCode.AUTH_UNKNOWN);
                    }
                }else {
                    return DtoUtil.returnFail("激活码错误", ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }

            }else {
                return DtoUtil.returnFail("用户名已经激活", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }

        }else {
            return DtoUtil.returnFail("用户名不存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
        }
    }

    /**
     * 邮箱注册用户激活
     */
    @ApiOperation(value = "邮箱注册用户激活")
    @RequestMapping(value = "/validatephone", method = RequestMethod.PUT, produces = "application/json")
    public Dto validatephone(@RequestParam("user") String user,@RequestParam("code") String code) {
        try {
            return attributeUser(user,code);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 用户登录
     * @param name
     * @param password
     * @return
     */
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/dologin", method = RequestMethod.POST , produces = "application/json")
    public Dto doLogin(@RequestParam("name") String name, @RequestParam("password") String password,HttpServletRequest request) {
        try {
            //1.非空验证用户不为空
            if (name.isEmpty() && password.isEmpty()){
                return DtoUtil.returnFail("用户名密码不能为空", ErrorCode.AUTH_PARAMETER_ERROR);
            }
                //request.getHeader("user-agent")表示：使服务器能够识别客户使用的操作系统及版本
                 return userService.doLogin(name,password,request.getHeader("user-agent"));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }


    /**
     * 注销用户
     * @return
     */
    @ApiOperation(value = "注销用户")
    @RequestMapping(value = "/logout", method = RequestMethod.GET , produces = "application/json")
    public Dto logout(HttpServletRequest request) {
        //获取Header中的数据
        String token = request.getHeader("token");
        try {
            if (tokenService.deleteToken(token)){
                return DtoUtil.returnSuccess();
            }
            return DtoUtil.returnFail("注销失败", ErrorCode.AUTH_UNKNOWN);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

    @ApiOperation(value = "客户端置换tooken")
    @RequestMapping(value = "/retoken", method = RequestMethod.POST , produces = "application/json")
    public Dto retoken(HttpServletRequest request) {
        //获取Header中的数据
//        String token = "token:PC-f3cf2a9a14a660c74cfe808385361836-46-20191009005229-40d2af";
        String token=request.getHeader("token");
        try {
            if (token !=null && tokenService.exit(token)){
                if (tokenService.getTll(token)>(5*60)){
                    return DtoUtil.returnFail("tooken时间还长", ErrorCode.AUTH_TOKEN_INVALID);
                }

                //给token续命
                if (!tokenService.expire(token)){
                    return DtoUtil.returnFail("token置换失败", ErrorCode.AUTH_TOKEN_INVALID);
                }
                //获取tooken的value值
                String tokenValue=tokenService.getValue(token);
                ItripUser user = JSON.parseObject(tokenValue, ItripUser.class);
                TokenVO tokenVO = tokenService.genToken(request.getHeader("user-agent"), user);
                return DtoUtil.returnDataSuccess(tokenVO);
            }
                return DtoUtil.returnFail("token已失效", ErrorCode.AUTH_TOKEN_INVALID);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("服务器未响应", ErrorCode.AUTH_UNKNOWN);
        }
    }

}
